<?php

declare(strict_types=1);

namespace app\utils;

use think\exception\Handle;
use think\exception\HttpException;
use think\exception\ValidateException;
use think\Response;
use Throwable;


/**
 * 自定义异常处理类
 */
class MyException extends Handle
{
    public function render($request, Throwable $e): Response
    {
        // 自定义异常处理机制
        // 参数验证错误
        if ($e instanceof ValidateException) {
            return json(['code' => 422, 'msg' => $e->getError()], 422);
        }

        // 请求异常
        if ($e instanceof HttpException) {
            // ajax请求
            if ($request->isAjax()) {
                return json(['code' => $e->getStatusCode(), 'msg' => $e->getMessage()], $e->getStatusCode());
            } else {    // html请求
                $status = $e->getStatusCode();
                switch ($status) {
                    case 400:
                        return response('400，错的请求！');
                        break;
                    case 404:
                        return response('404，页面未找到！');
                        break;
                    case 500:
                        return response('404，服务端出现错误！');
                        break;
                    default:
                        return response("{$status}，访问出现问题！");
                        break;
                }
            }
        }


        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}